import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from "react";
import purchaseReceiptService from "@/api/services/wms/purchaseReceiptService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import { Button, DatePicker, Input, InputNumber } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { toast } from "sonner";
import type { WmsPurchaseReceiptDetail } from "./entity";
import TableDictTag from "@/components/grid/TableDictTag";
import dayjs from "dayjs";
import { el } from "@faker-js/faker";

interface ReceiptMaterialProps {
  parentId?: React.Key;
}

export interface ReceiptMaterialHandles {
  getAddList: () => WmsPurchaseReceiptDetail[];
  getUpdateList: () => WmsPurchaseReceiptDetail[];
  getDeleteIds: () => React.Key[];
}

const ReceiptMaterialPage = forwardRef<
  ReceiptMaterialHandles,
  ReceiptMaterialProps
>(({ parentId }, ref) => {
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<WmsPurchaseReceiptDetail[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [editedRowKey, setEditedRowKey] = useState<React.Key>();
  // 添加一个状态来跟踪临时ID
  const [tempIds, setTempIds] = useState<React.Key[]>([]);
  const [addList, setAddList] = useState<WmsPurchaseReceiptDetail[]>([]);
  const [updateList, setUpdateList] = useState<WmsPurchaseReceiptDetail[]>([]);
  const [deleteIds, setDeleteIds] = useState<React.Key[]>([]);

  useImperativeHandle(
    ref,
    () => ({
      getAddList: () => addList,
      getUpdateList: () => updateList,
      getDeleteIds: () => deleteIds,
    }),
    [addList, updateList, deleteIds]
  );

  useEffect(() => {
    const newAddList = list.filter(
      (item) => item.id && tempIds.includes(item.id)
    );
    setAddList(newAddList);
    const updateList = list.filter(
      (item) => item.id && !tempIds.includes(item.id)
    );
    setUpdateList(updateList);
  }, [list]);

  const [tableSize, setTableSize] = useState<"large" | "middle" | "small">(
    "middle"
  );

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 403;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  //表格列定义
  const columns: ColumnsType<WmsPurchaseReceiptDetail> = [
    {
      title: "状态",
      width: 120,
      align: "center",
      key: "status",
      dataIndex: "status",
      render: (text, record) => (
        <TableDictTag
          dictCode="purchase_receipt_detail_status"
          value={record.status ?? "save"}
        />
      ),
    },
    {
      title: "物料编码",
      width: 150,
      key: "materialCode",
      dataIndex: "materialCode",
    },
    {
      title: "物料名称",
      width: 200,
      key: "materialName",
      dataIndex: "materialName",
    },
    {
      title: "预收数量",
      width: 120,
      key: "advanceQty",
      dataIndex: "advanceQty",
    },
    {
      title: "赠品数",
      width: 120,
      key: "giftQty",
      dataIndex: "giftQty",
      render: (text, record) => (
        <Input
          value={text}
          onChange={(e) =>
            handleFieldChange(record.id, "giftQty", e.target.value)
          }
          allowClear
        />
      ),
    },
    {
      title: "实收数量",
      width: 120,
      key: "actuallyQty",
      dataIndex: "actuallyQty",
      render: (text, record) => (
        <Input
          value={text}
          onChange={(e) =>
            handleFieldChange(record.id, "actuallyQty", e.target.value)
          }
          allowClear
        />
      ),
    },
    {
      title: "待送检数",
      width: 120,
      key: "toInspectQty",
      dataIndex: "toInspectQty",
      render: (text, record) =>
        record.actuallyQty && record.actuallyQty - (record.inspectedQty ?? 0),
    },
    {
      title: "已送检数",
      width: 120,
      key: "inspectedQty",
      dataIndex: "inspectedQty",
    },
    {
      title: "入库批次号",
      width: 120,
      key: "lotNo",
      dataIndex: "lotNo",
      render: (text, record) => (
        <Input
          value={text}
          onChange={(e) =>
            handleFieldChange(record.id, "lotNo", e.target.value)
          }
          allowClear
        />
      ),
    },
    {
      title: "生产日期",
      width: 120,
      key: "productionDate",
      dataIndex: "productionDate",
      render: (text, record) => (
        <DatePicker
          value={text ? dayjs(text) : null}
          style={{ width: "100%" }}
          format="YYYY-MM-DD"
          onChange={(date) =>
            handleFieldChange(record.id, "productionDate", date)
          }
        />
      ),
    },
    {
      title: "保质期（天）",
      width: 120,
      key: "shelfLifeDays",
      dataIndex: "shelfLifeDays",
      render: (text, record) => (
        <InputNumber
          value={text}
          onChange={(value) =>
            handleFieldChange(record.id, "shelfLifeDays", value)
          }
          style={{ width: "100%" }}
        />
      ),
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
      render: (text, record) => (
        <Input
          value={text}
          onChange={(e) =>
            handleFieldChange(record.id, "remark", e.target.value)
          }
        />
      ),
    },
    {
      title: "检验结果",
      width: 120,
      key: "checkResult",
      dataIndex: "checkResult",
      render: (_, record) => (
        <TableDictTag
          dictCode="check_result"
          value={record.checkResult ?? ""}
        />
      ),
    },
  ];

  const [selectedValues, setSelectedValues] = useState<string[]>(() =>
    columns
      .filter((col) => col.key !== "operation")
      .map((col) => (col.key ? String(col.key) : ""))
  );

  // 处理字段变更
  const handleFieldChange = (id: string, field: string, value: any) => {
    let inputValue: any = null;
    // 如果是checkbox的值，将布尔值转换为数字值（true为1，false为0）
    if (typeof value === "boolean") {
      inputValue = value ? 1 : 0;
    } else if (value instanceof Date) {
      // 处理日期格式
      inputValue = dayjs(value).format("YYYY-MM-DD");
    } else {
      inputValue = value;
    }

    setList((prevData) =>
      prevData.map((item) =>
        item.id === id ? { ...item, [field]: inputValue } : item
      )
    );
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  const filteredColumns = useMemo(() => {
    return [
      ...columns.filter(
        (col) =>
          selectedValues.includes(String(col.key)) || col.key === "operation"
      ),
    ].sort((a, b) => {
      const originalIndex = columns.findIndex((c) => c.key === a.key);
      const targetIndex = columns.findIndex((c) => c.key === b.key);
      return originalIndex - targetIndex;
    });
  }, [selectedValues]);

  //加载表格数据
  const fetchList = () => {
    if (!parentId) return;

    setLoading(true);
    purchaseReceiptService
      .getdetails(parentId)
      .then((res) => {
        setList(res);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    if (parentId) {
      fetchList();
    } else {
      // 初始化时清空状态
      setList([]);
      setSelectedRowKeys([]);
      setTempIds([]);
      setAddList([]);
      setUpdateList([]);
      setDeleteIds([]);
    }
  }, [parentId]);

  //检验是否输入值
  const validatePartsBeforeAdd = (): boolean => {
    for (const detail of list) {
      if (!detail.actuallyQty) {
        toast.error("实收数量不能为空");
        return false;
      } else if (detail.actuallyQty < 0) {
				toast.error("实收数量不能为负数");
				return false;
			} else if (detail.actuallyQty > detail.advanceQty + (detail.giftQty ?? 0)) {
				toast.error("实收数量不能大于预收数量与赠品数之和");
				return false;
			}
    }
    return true;
  };

	// 送检
	const handleInspect = () => {
		if (!validatePartsBeforeAdd()) {
			return; // 校验未通过，不执行新增
		}

		if (selectedRowKeys.length === 0) {
			toast.error("请选择要送检的行！");
			return;
		}

		const inspectList = list.map((item) => {
			if (selectedRowKeys.includes(item.id)) {
				return item;
			}
			return item;
		});

		
	};

  return (
    <>
      <div className="flex justify-between mb-4">
        <div className="flex gap-2">
          <Button type="primary" onClick={handleInspect}>
            送检
          </Button>
        </div>
        <TableToolbar
          onRefresh={() => fetchList()}
          onSizeChange={setTableSize}
          columns={columns}
          selectedValues={selectedValues}
          onColumnChange={setSelectedValues}
        />
      </div>
      <Table
        rowKey="id"
        size={tableSize}
        scroll={{ x: "max-content", y: tableScrollY }}
        loading={loading}
        pagination={false}
        columns={filteredColumns}
        dataSource={list}
        rowSelection={{
          type: "checkbox",
          selectedRowKeys: selectedRowKeys,
          onChange: (selectedKeys) => {
            setSelectedRowKeys(selectedKeys as React.Key[]);
          },
        }}
      />
    </>
  );
});

export default ReceiptMaterialPage;
